package com.freeheart.validation.constraintvalidators.recent;


import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

/**
 * @author: EmperorHeart
 * @date: 2025/5/10 1:32
 * @description
 */
public class ComputeGapForDate implements ComputeGap {

    @Override
    public boolean support(Object obj) {
        return obj instanceof Date;
    }

    @Override
    public long compute(Object obj, RecentProperties rp) {
        Date date = (Date) obj;
        LocalDateTime dt = transform(date);
        if (rp.isTruncate()) {
            return rp.currentUnit().between(dt.truncatedTo(rp.currentUnit()),
                    LocalDateTime.now().truncatedTo(rp.currentUnit()));
        }
        return rp.currentUnit().between(dt, LocalDateTime.now());
    }


    private LocalDateTime transform(Date date) {
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        return LocalDateTime.ofInstant(instant, zoneId);
    }
}
